package Net.tcp.chat4;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * 发送端
 */
public class Send implements Runnable {
   private DataOutputStream dos = null;
   private Socket client;
    private BufferedReader console = null;
    boolean isRunning = true;
    private String name;
   public Send(Socket client,String name){
       this.client=client;
       this.name =name;
       console = new BufferedReader(new InputStreamReader(System.in));
       try {
           dos =  new DataOutputStream(client.getOutputStream());//getOutputStream返回此套接字的输出流。
           //发送名称
           send(name);
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

    //释放资源
    private void release(){
        this.isRunning=false;
        Utils.close(dos,client);
    }

    //发送
    private void send(String msg){
        if(!msg.equals("")){
            try {
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                release();
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        while (isRunning){
            String msg = "";
            try {
                msg = console.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            send(msg);
        }
    }
}
